from flask import request
from flask import redirect
from flask_restplus import Resource, Namespace, fields
from ..models import GoodsModel, db

ns = Namespace("商品接口", path="/goods", description="接口描述信息")

expect_fields = ns.model("resource_request", {
    "goods_name": fields.String(max_length=20,
                                required=True,
                                description="商品名称"),
    "goods_id": fields.Integer(required=True,
                               description="商品ID"),
    "goods_price": fields.Float(required=True,
                                description="商品价格"),
})


rsp_model = ns.model("resource_response", {
    "goods_name": fields.String(max_length=20,
                                required=True,
                                description="商品名称"),
    "goods_id": fields.Integer(required=True,
                               description="商品ID"),
    "goods_price": fields.Float(required=True,
                                description="商品价格"),
    "inventory": fields.Integer(required=True,
                                description="库存数量"),
})


responses = {
    200: "操作成功",
    201: "资源创建成功",
    400: "参数有误",
    404: "资源不存在",
    500: "服务内部错误"
}


@ns.route("/")
class Goods(Resource):

    # @ns.param("goods_ids", description="商品ID", required=True)
    # @ns.doc(responses={
    #     200: "请求成功",
    #     204: "空资源",
    #     400: "参数有误",
    #     404: "资源不存在",
    #     500: "服务内部错误"
    # })
    @ns.marshal_with(rsp_model, envelope="resource", as_list=True)
    def get(self, *args, **kwargs):
        """
        获取商品信息
        """
        goods = db.session.query(GoodsModel).first()
        return goods

    @ns.expect(expect_fields, validate=True)
    @ns.doc(responses={
        200: "操作成功",
        204: "空资源",
        400: "参数有误",
        404: "资源不存在",
        500: "服务内部错误"
    })
    def post(self):
        """
        新增商品信息
        """
        data = request.get_json()
        record = db.session.query(GoodsModel).filter(
            GoodsModel.goods_id == data["goods_id"]).first()
        if record:
            print("记录已经存在.")
            return {"message": "success", "code": 201}, 201
        goods = GoodsModel(**request.get_json())
        db.session.add(goods)
        return {"message": "success", "code": 201}, 201


@ns.route("/<string:goods_id>")
@ns.param("goods_id", "商品ID")
@ns.doc(responses=responses)
class GoodsUpdating(Resource):

    def delete(self, goods_id):
        """
        删除商品信息
        """

        ns.abort(404, message="资源不存在")
        return '', 200

    @ns.expect(expect_fields, validate=True)
    def put(self, goods_id):
        """
        更新商品信息
        """
        # data = request.get_json()
        goods = db.session.query(GoodsModel).filter_by(goods_id=goods_id).first()
        if not goods:
            ns.abort(404, message="资源不存在")

        db.session.add(goods)
        return "updated", 200
